#include <iostream>
#include <string>
#include <unistd.h>
#include <ctime>

#include "./source/Server.hpp"

class test
{
public:
    test()
    {
        std::cout << "构造" << std::endl;
    }
    test(const test& t)
    {
        std::cout << "拷贝构造" << std::endl;
    }
    ~test()
    {
        std::cout << "析构" << std::endl;
    }
};

void Deltest(test* t)
{
    delete t;
}

void testTimeWheel()
{
    // TimeWheel tw;
    // test* t = new test();
    // tw.AddTimerTask(8888, 5, std::bind(Deltest, t));

    // for (int i = 0; i < 5; i++)
    // {
    //     sleep(1);
    //     tw.RunTimerTask();
    //     tw.RefreshTimerTask(8888);
    //     std::cout << "刷新了一下定时任务，重新需要5s后才会销毁\n";
    // }
    // tw.CancelTimerTask(8888);
    // while (true)
    // {
    //     sleep(1);
    //     std::cout << "--------------------\n";
    //     tw.RunTimerTask();
    // }
}

void testAny()
{
    Any a;
    {
        test t;
        a = t;
    }
    // a = 10;
    // int *pa = a.Get<int>();
    // std::cout << *pa << std::endl;
    // a = std::string("你好");
    // std::string* sa = a.Get<std::string>();
    // std::cout << *sa << std::endl;
    // a = Any(100);
    // Any b = "300";
    // a = b;
    // std::cout << *sa << std::endl;
    while (true) sleep(1);
}

void testBuffer()
{
    Buffer buf;
    for (int i = 0; i < 300; i++)
    {
        std::string str = "你好" + std::to_string(i) + '\n';
        buf.Write(str);
    }
    while (buf.GetReadableSize() > 0)
    {
        std::string line = buf.GetLine();
        std::cout << line << std::endl;
    }
    // std::string tmp;
    // buf.Read(tmp, buf.GetReadableSize());
    // std::cout << tmp << std::endl;


    // buf.Write(t);

    // Buffer buf1;
    // buf1.Write(buf);

    // std::string tmp;
    // buf1.Read(tmp, buf1.GetReadableSize());

    // std::cout << tmp << std::endl;
    // std::cout << buf.GetReadableSize() << std::endl;
    // std::cout << buf1.GetReadableSize() << std::endl;
}


void testlog()
{
    INFO_LOG("你好");
}

// void HandleClose(Connection* connection)
// {
//     // std::cout << "close: " << channel->GetSockfd() << std::endl;
//     DEBUG_LOG("close: %d", connection->GetSockfd());
//     channel->Remove(); // 关闭监控
//     delete channel;
// }

// void HandleRead(Connection* connection)
// {
//     int fd = connection->GetSockfd();
//     char buf[1024] = { 0 };
//     int n = ::recv(fd, buf, sizeof(buf) - 1, 0);
//     if (n <= 0)
//     {
//         ConnectionDestroy(connection); // 关闭释放
//         return;
//     }
//     DEBUG_LOG("%s", buf);
//     // std::cout << buf << std::endl;
//     connection->EnableWrite(); // 启动可写事件
// }

// void HandleWrite(Connection* connection)
// {
//     int fd = connection->GetSockfd();
//     const char* data = "天气还不错！";
//     int n = ::send(fd, data, strlen(data), 0);
//     if (n < 0)
//     {
//         ConnectionDestroy(connection); // 关闭释放
//         return;
//     }
//     connection->DisableWrite(); // 关闭写监控
// }

// void HandleError(Connection* connection)
// {    
//     HandleClose(connection); // 关闭释放
// }

// void HandleEvent(EventLoop* eloop, Connection* connection, uint64_t timerid)
// {
//     // std::cout << "有了一个事件\n";
//     eloop->RefreshTimerTask(timerid);
// }

// 管理所有连接
std::unordered_map<uint64_t, Connection::connection_ptr> _connections;
uint64_t connection_id = 0;

EventLoop base_loop;
int nextloop = 0;
ThreadLoopPool* threads;

void ConnectionDestroy(const Connection::connection_ptr& connetion)
{
    _connections.erase(connetion->GetConnectionid());
}

void OnConnected(const Connection::connection_ptr& connetion)
{
    DEBUG_LOG("new connection:%p", connetion.get());
}

void OnMessage(const Connection::connection_ptr& connection, Buffer* buf)
{
    std::string clientmessage;
    buf->Read(&clientmessage, buf->GetReadableSize());
    DEBUG_LOG("%s", clientmessage.c_str());
    std::string str = "Hello Client!";
    connection->Send(str.c_str(), str.length());
    connection->ShutDown();
}

void NewConnection(int newfd)
{
    connection_id++;
    Connection::connection_ptr connection = std::make_shared<Connection>(threads->GetNextEventLoop(), connection_id, newfd);
    connection->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    connection->SetServerClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    connection->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    connection->EnableInactiveRelease(10); // 启动非活跃超时销毁
    connection->Established(); // 就绪初始化
    _connections.insert(std::make_pair(connection_id, connection));
}

void Acceptor2(EventLoop* eloop, Channel* listen)
{
    int fd = listen->GetSockfd();
    struct sockaddr_in addr;
    socklen_t len = sizeof addr;
    int newfd = ::accept(fd, reinterpret_cast<struct sockaddr*>(&addr), &len);
    if (newfd < 0) return;
    connection_id++;
    Connection::connection_ptr connection = std::make_shared<Connection>(eloop, connection_id, newfd);
    connection->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    connection->SetServerClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    connection->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    connection->EnableInactiveRelease(10); // 启动非活跃超时销毁
    connection->Established(); // 就绪初始化
    _connections.insert(std::make_pair(connection_id, connection));
}

void testTcpServer()
{
    threads = new ThreadLoopPool(&base_loop);
    threads->SetThreadCount(2);
    threads->Run();
    // 为监听套接字，创建每一个Channel进行事件的管理，以及事件的处理
    Acceptor acceptor(&base_loop, 8888);
    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1)); // 回调中，获取新连接，为新连接创建的channel并添加监控
    acceptor.Listen();
    base_loop.Start();
}

int main()
{
    // testTimeWheel();
    // testAny();
    // testBuffer();
    // testlog();
    testTcpServer();

    return 0;
}